package com.springBoot.springBootSysCore.common.third.oss.test.my;

import java.beans.PropertyEditorSupport;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.sql.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.aliyun.oss.model.BucketInfo;
import com.springBoot.springBootSysCore.common.config.Global;
import com.springBoot.springBootSysCore.common.utils.DateUtils;
import com.springBoot.springBootSysCore.common.utils.IdGen;
import com.springBoot.springBootSysCore.common.utils.IdcardUtils;
import com.springBoot.springBootSysCore.common.utils.encoding.Encodes;
import com.springBoot.springBootSysCore.common.utils.json.JsonUtil;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

/**
 * Created by timo on 2018/1/3.
 */
//@WebServlet(asyncSupported = true, name = "osssignuature", urlPatterns = "/osssignuature")
public class OssPostObjectPolicy extends HttpServlet {
    /**
     *
     */
    private static final long serialVersionUID = 5522372203700422672L;

    String endpoint = Global.getConfig("oss.endpoint");
    String accessId = Global.getConfig("oss.accessKeyId");
    String accessKey = Global.getConfig("oss.accessKeySecret");
    String bucket = Global.getConfig("oss.bucketName");

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String dir = "user-dir";
        if (null != request.getParameter("dir")) {
            dir = request.getParameter("dir");
        }
        String host = "http://" + bucket + "." + endpoint;

        String endpoints = "http://" + endpoint;
        OSSClient client = new OSSClient(endpoints, accessId, accessKey);
        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

//            BucketInfo info = client.getBucketInfo(bucket);
//            System.out.println("Bucket: " + bucket + "的信息如下：");
//            System.out.println("\t数据中心：" + info.getBucket().getLocation());
//            System.out.println("\t创建时间：" + info.getBucket().getCreationDate());
//            System.out.println("\t用户标志：" + info.getBucket().getOwner());
            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = client.calculatePostSignature(postPolicy);

            Map<String, String> respMap = new LinkedHashMap<String, String>();
            respMap.put("accessid", accessId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            //respMap.put("expire", formatISO8601Date(expiration));
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));

            Map celMap = new HashedMap();
            celMap.put("callbackUrl",request.getParameter("callback"));
            celMap.put("callbackBodyType","application/json");
            celMap.put("callbackBody","bucket=${bucket}&object=${object}&etag=${etag}&size=${size}&mimeType=${mimeType}&my_var=${x:var}");
            /*" +
            "&imageInfo.height=${imageInfo.height}&imageInfo.width=${imageInfo.width}" +
                    "&imageInfo.format=${imageInfo.format}*/

            respMap.put("callback", Encodes.encodeBase64(JsonUtil.objToJson(celMap).toString().getBytes()));
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "GET, POST");
            response.setHeader("Access-Control-Allow-Credentials", "true");

            response(request, response, JsonUtil.objToJson(respMap));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void response(HttpServletRequest request, HttpServletResponse response, String results) throws IOException {
        response.getWriter().println(results);
        response.setStatus(HttpServletResponse.SC_OK);
        response.flushBuffer();
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        // String类型转换，将所有传递进来的String进行HTML编码，防止XSS攻击
        binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(text == null ? null : StringEscapeUtils.escapeHtml4(text.trim()));
            }

            @Override
            public String getAsText() {
                Object value = getValue();
                return value != null ? value.toString() : "";
            }
        });
    }

}